package cn.yh.register.hosp.service.impl;

import cn.yh.register.client.cmn.CmnDictClient;
import cn.yh.register.enums.DictEnum;
import cn.yh.register.hosp.repository.HospitalRepository;
import cn.yh.register.hosp.service.HospitalService;
import cn.yh.register.model.hosp.Hospital;
import cn.yh.register.vo.hosp.HospitalQueryVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    HospitalRepository hospitalRepository;

    @Autowired
    CmnDictClient client;


    /**
     * 保存医院信息
     *
     * @param objectMap 医院信息
     */
    @Override
    public void saveHospital(Map<String, Object> objectMap) {
        //为方便操作 将数据转对象
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(objectMap), Hospital.class);
        //先查询数据库已存在
        Hospital hosp = hospitalRepository.findByHoscode(hospital.getHoscode());
        if (hosp == null) {
            //新增
            hospital.setCreateTime(new Date());
            hospital.setIsDeleted(0);
            hospital.setStatus(0);//0 ：未上线  1：已上线

        } else {
            //修改
            hospital.setId(hosp.getId());
            hospital.setCreateTime(hosp.getCreateTime());
            hospital.setStatus(0);//0 ：未上线  1：已上线
            hospital.setIsDeleted(hosp.getIsDeleted());

        }
        hospital.setCreateTime(new Date());
        hospitalRepository.save(hospital);

    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.findByHoscode(hoscode);
    }

    /**
     * 分页查询
     *
     * @param page            当前页码
     * @param limit           每页记录条数
     * @param hospitalQueryVo 查询条件
     * @return
     */
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Hospital hospital = new Hospital();
        hospital.setIsDeleted(0);
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        PageRequest pageRequest = PageRequest
                .of(page - 1, limit, Sort.by(Sort.Direction.DESC, "createTime"));
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()  //构建条件对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)  //更改默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        Example<Hospital> example = Example.of(hospital, matcher);
        //分页查询
        Page<Hospital> pages = hospitalRepository.findAll(example, pageRequest);
        pages.getContent().forEach(this::packHospital);

        return pages;
    }

    /**
     * 更新上线状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(String id, Integer status) {
        if (status == 0 || status == 1){
            Optional<Hospital> hospital = hospitalRepository.findById(id);
            if (hospital.isPresent()) {
                hospital.get().setStatus(status);
                hospital.get().setUpdateTime(new Date());
                hospitalRepository.save(hospital.get());
            }
        }
    }

    /**
     * 查看医院详情
     *
     * @param id 医院id
     * @return 医院基本信息 & 预约规则
     */
    @Override
    public Map<String, Object> show(String id) {
        Optional<Hospital> hospital = hospitalRepository.findById(id);
        if (hospital.isPresent()) {
            Hospital hosp = hospital.get();
            this.packHospital(hosp);
            Map<String,Object> map = new HashMap<>();
            map.put("bookingRule",hosp.getBookingRule());
            map.put("hospital",hosp);
            //因为预约规则单独返回，所以hospital对象中不需要单独返回
            hosp.setBookingRule(null);
            return map;
        }
        return null;
    }

    /**
     * 根据医院名称模糊查询
     *
     * @param hosname 医院名称
     * @return 医院列表
     */
    @Override
    public List<Hospital> findByHosname(String hosname) {
        return hospitalRepository.findByHosnameLike(hosname);
    }

    /**
     * 查看医院详情
     *
     * @param hoscode 医院编号
     * @return 医院基本信息 & 预约规则
     */
    @Override
    public Map<String, Object> item(String hoscode) {
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        if (hospital != null) {
            this.packHospital(hospital);
            Map<String,Object> map = new HashMap<>();
            map.put("bookingRule",hospital.getBookingRule());
            map.put("hospital",hospital);
            //因为预约规则单独返回，所以hospital对象中不需要单独返回
            hospital.setBookingRule(null);
            return map;
        }
        return null;
    }


    //处理医院数据
    private void packHospital (Hospital hospital){
        //医院等级
        String hosTypeString = client.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        //省编码
        String provice = client.getName(hospital.getProvinceCode());
        //市编码
        String city = client.getName(hospital.getCityCode());

        //区编码
        String district = client.getName(hospital.getDistrictCode());
        //装入param属性
        hospital.getParam().put("hosTypeString",hosTypeString);
        hospital.getParam().put("fullAddress",provice+city+district+hospital.getAddress());


    }

}
